package com.capinfo.accumulation.web.controller.collection;


import com.capinfo.accumulation.model.collection.*;
import com.capinfo.accumulation.parameter.collection.PauseRecoveryRecordParameter;
import com.capinfo.accumulation.service.collection.CompanyAccountFundService;
import com.capinfo.accumulation.service.collection.PauseRecoveryRecordService;
import com.capinfo.accumulation.service.collection.PersonService;
import com.capinfo.commons.project.model.security.SystemUser;
import com.capinfo.commons.project.parameter.security.SystemResourceParameter;
import com.capinfo.framework.model.dictionary.Dictionary;
import com.capinfo.framework.service.CommonsDataOperationService;
import com.capinfo.framework.util.IOUtils;
import com.capinfo.framework.util.LogUtils;
import com.capinfo.framework.web.Constants;
import com.capinfo.framework.web.controller.CommonsDataManageController;
import com.capinfo.framework.web.util.ControllerUtils;
import com.capinfo.framework.web.util.WebRequestUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Rexxxar on 2017/10/18.
 */
@Controller
@RequestMapping("/business/collection/pause_recovery_record")
public class PauseRecoveryRecordController extends CommonsDataManageController<PauseRecoveryRecordParameter,PauseRecoveryRecord> {

    private static final Log logger = LogFactory.getLog(PauseRecoveryRecord.class);

    @Autowired
    private PauseRecoveryRecordService pauseRecoveryRecordService;

    @Autowired
    private PersonService personService;

    @Autowired
    private CompanyAccountFundService companyAccountFundService;

    ;




    /**
     * 弹出处理菜单
     *@Author: Rexxxar
     *@Description
     *@Date: 2017/10/26 14:17
     */
    @RequestMapping("deal.shtml")
    public Map<String, Object> tree(NativeWebRequest request, PauseRecoveryRecordParameter parameter) {

        Map<String, Object> viewModel = new HashMap<String, Object>();

        return viewModel;
    }

    /**
     * 弹出清册公司
     *@Author: Rexxxar
     *@Description
     *@Date: 2017/10/26 14:17
     */
    @RequestMapping("/add.shtml")
    public Map<String, Object> initial(NativeWebRequest request, PauseRecoveryRecordParameter parameter) {

        Map<String, Object> viewModel = new HashMap<String, Object>();

        return viewModel;
    }

    /**
     * 弹出确认名单
     *@Author: Rexxxar
     *@Description
     *@Date: 2017/10/26 14:17
     */
    @RequestMapping("/confirm.shtml")
    public Map<String, Object> confirm(PauseRecoveryRecordParameter parameter) {
        return ControllerUtils.buildViewModel(parameter);
    }

    @RequestMapping("/record_list.shtml")
    public Map<String , Object> insert_message(NativeWebRequest request, PauseRecoveryRecordParameter parameter){
        Map<String, Object> viewModel = new HashMap<String, Object>();
        return viewModel;
    }

    /**
     * 点击录入，显示单位账号和单位名称
     * 个人缴存比例 单位缴存比例
     *@Author: Rexxxar
     *@Description
     *@Date: 2017/11/2 11:29
     */
    @RequestMapping("/record_form.shtml")
    public ModelAndView recordForm (NativeWebRequest request, PauseRecoveryRecordParameter parameter){

        ModelAndView mav = new ModelAndView();

        Long id =(Long) WebRequestUtils.retrieveSessionAttribute(request, "pauseRecoveryInventoryId");
        String account =(String) WebRequestUtils.retrieveSessionAttribute(request, "inventoryFund");

        CompanyAccountFund companyAccountFund = pauseRecoveryRecordService.searchCompanyAccountAndName(account);

       /* Set<Dictionary> contactIdCardTypeIdList = companyAccountFundService.getDictionariesBySortName("证件类型");
        mav.addObject("contactIdCardTypeIdList",contactIdCardTypeIdList);

        if(parameter.getPauseRecoveryInventoryFlag()==1){
            Set<Dictionary> pauseRecoveryReason = companyAccountFundService.getDictionariesBySortName("停缴原因");
            mav.addObject("pauseRecoveryReason",pauseRecoveryReason);
        }
        if(parameter.getPauseRecoveryInventoryFlag()==2){
            Set<Dictionary> pauseRecoveryReason = companyAccountFundService.getDictionariesBySortName("启封原因");
            mav.addObject("pauseRecoveryReason",pauseRecoveryReason);
        }*/

        mav.addObject("companyAccountFund",companyAccountFund);
        mav.addObject("pauseRecoveryInventoryFlag",parameter.getPauseRecoveryInventoryFlag());
        mav.setViewName("/business/collection/pause_recovery_record/record_form");

        return mav;

    }

    /**
     * 验证单位账号是否存在
     *@Author: Rexxxar
     *@Description
     *@Date: 2017/10/26 14:35
     */
    @RequestMapping("/check.shtml")
    @ResponseBody
    public String recoveryCheckAccount(String companyAccount) throws UnsupportedEncodingException {
        boolean flag = pauseRecoveryRecordService.recoveryCheckAccount(companyAccount);
        JSONObject json = new JSONObject();
        json.put("result",flag);
        return json.toString();

    }

    /**验证个人是否可以停复缴
     *@Author: Rexxxar
     *@Description
     *@Date: 2017/11/2 15:18
     */
    @RequestMapping("/check_people.shtml")
    @ResponseBody
    public String recoveryCheckPeople(NativeWebRequest request,String idCardNumber,Long pauseRecoveryInventoryFlag) throws UnsupportedEncodingException {
        JSONObject json = new JSONObject();
        json.toString().getBytes("UTF-8");
        String account =(String) WebRequestUtils.retrieveSessionAttribute(request, "inventoryFund");

        json = pauseRecoveryRecordService.recoveryCheckPeople(account,idCardNumber,pauseRecoveryInventoryFlag);


        return json.toString();




    }



    /**停缴处理删除
     *
     *@Author: Rexxxar
     *@Description
     *@Date: 2017/10/23 21:11
     */
    @RequestMapping("/delete_pause_record.shtml")
    public void deletePauseRecord(NativeWebRequest request, PauseRecoveryRecordParameter pauseRecoveryRecordParameter, OutputStream stream) {

        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);


        JSONObject jsonObject = new JSONObject();

        try {
            pauseRecoveryRecordService.delete(pauseRecoveryRecordParameter);
            jsonObject.put("result", "true");

        } catch (Exception e) {

            jsonObject.put("result", "false");
            LogUtils.debugException(logger, e);
        }

        try {

            IOUtils.outputByStream(stream, jsonObject.toString().getBytes("UTF-8"));

        } catch (UnsupportedEncodingException e) {

            LogUtils.debugException(logger, e);
        }


    }



    /**
     * 通过字典类型查询下拉框选项
     *@Author: Rexxxar
     *@Description
     *@Date: 2017/10/26 14:35
     */
    @RequestMapping("/searchListBySortId.shtml")
    public void searchListBySortId(Long sortId,OutputStream stream) throws UnsupportedEncodingException {
        List optionFundList = pauseRecoveryRecordService.optionFund(sortId);

        try {

            IOUtils.outputByStream(stream, JSONArray.fromObject(optionFundList).toString().getBytes("UTF-8"));

        } catch (UnsupportedEncodingException e) {

            LogUtils.debugException(logger, e);
        }
    }

    /**
     * 字典项
     *@Author: Rexxxar
     *@Description
     *@Date: 2017/10/24 10:28
     */
    protected Map<String, Object> formOptionAfterInvoke(PauseRecoveryRecordParameter parameter, Map<String, Object> viewModel) {

        Set<Dictionary> contactIdCardTypeIdList = pauseRecoveryRecordService.getDictionariesBySortName("证件类型");
        viewModel.put("contactIdCardTypeIdList",contactIdCardTypeIdList);
        Set<Dictionary> recoveryReasonList = pauseRecoveryRecordService.getDictionariesBySortName("启封原因");
        viewModel.put("recoveryReasonList",recoveryReasonList);
        Set<Dictionary> pauseReasonList = pauseRecoveryRecordService.getDictionariesBySortName("停缴原因");
        viewModel.put("pauseReasonList",pauseReasonList);
        Set<Dictionary> fundOptionList = pauseRecoveryRecordService.getDictionariesBySortName("停复缴选项");
        viewModel.put("fundOptionList",fundOptionList);


        return viewModel;
    }

    /**
     * 创建清册表单
     *@Author: Rexxxar
     *@Description
     *@Date: 2017/10/30 21:33
     */
    @RequestMapping("create_inventory.shtml")
    public Map<String,Boolean> createInventory(NativeWebRequest request,PauseRecoveryRecordParameter pauseRecoveryRecordParameter){
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);
        Map<String,Boolean> map = new HashMap<>();
        SystemUser user  = (SystemUser)WebRequestUtils.retrieveSessionAttribute( request, Constants.ADMIN_ATTRIBUTE_KEY);

        try{
            /*pauseRecoveryRecordParameter.getEntityMessage().setOperatorId(user.getId());*/
            pauseRecoveryRecordService.createInventory(pauseRecoveryRecordParameter);
            map.put("result", true);
        }catch (Exception e){
            map.put("result", false);
            LogUtils.debugException(logger, e);
        }

        return map;
    }


    /**
     * 录入保存
     * 存入记录表
     *@Author: Rexxxar
     *@Description
     *@Date: 2017/10/27 14:16
     */
    @RequestMapping("recovery_save_or_update.shtml")
    @ResponseBody
    public Map<String,Boolean> saveOrUpdate(NativeWebRequest request, PauseRecoveryRecordParameter pauseRecoveryRecordParameter){
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);
        Map<String,Boolean> map = new HashMap<>();
        SystemUser user  = (SystemUser)WebRequestUtils.retrieveSessionAttribute( request, Constants.ADMIN_ATTRIBUTE_KEY);

        try{

            /*pauseRecoveryRecordParameter.getEntityMessage().setOperatorId(user.getId());*/
            pauseRecoveryRecordService.saveOrUpdateRecord(pauseRecoveryRecordParameter);
            map.put("result", true);
        }catch (Exception e){
            map.put("result", false);
            LogUtils.debugException(logger, e);
        }
        return map;
    }

   /**
    * 个人更换工作，判断原单位和新单位的缴存比例
    * 两个单位的缴存比例不一致时，
    * 按新单位的缴存比例进行缴存，启封时，
    * 录入新的工资收入，根据新的缴存比例，
    * 算出新的月缴存额.返回ture.
    * 返回缴存比例
    *@Author: Rexxxar
    *@Description
    *@Date: 2017/10/31 22:39
    */
   @RequestMapping("/check_ratio.shtml")
   @ResponseBody
   public String recoveryCheckratio(BigDecimal wageIncome, String companyAccount, String idCardNumber) throws UnsupportedEncodingException {

       JSONObject json = new JSONObject();
       json.toString().getBytes("UTF-8");
       json = pauseRecoveryRecordService.recoveryCheckratio(wageIncome,companyAccount,idCardNumber);
       return json.toString();
   }






    @Override
    public Map<String, Object> search(PauseRecoveryRecordParameter parameter) {
       return formOptionAfterInvoke(parameter,ControllerUtils.buildViewModel(parameter));
    }
    @Override
    public CommonsDataOperationService<PauseRecoveryRecord, PauseRecoveryRecordParameter> getCommonsDataOperationService() {
        return pauseRecoveryRecordService;
    }

}
